package com.rags.chess.move;

import java.util.Collection;

import com.rags.chess.base.Coordinate;
import com.rags.chess.base.Piece;
import com.rags.chess.game.Game;
import com.rags.chess.pieces.King;
import com.rags.chess.pieces.Pawn;

public class BasicMove extends Move {
	public BasicMove(Game game, Coordinate aStart, Coordinate anEnd) {
		super(game, aStart, anEnd, null);
	}
	
	@Override
	protected String deriveNotation(Game game, Coordinate start, Coordinate end) {
		Piece startPiece = game.getPiece(start);
		if (!startPiece.isValidMove(game, end))
			throw new IllegalArgumentException(String.format("Illegal Basic Move attempted: %s%s to %s", startPiece.getNotation(), start, end));
		if (startPiece instanceof Pawn && (end.getNotation().charAt(1) == '1' || end.getNotation().charAt(1) == '8'))
			throw new IllegalArgumentException(String.format("Promotion of a pawn: %s to %s is not a basic move", start, end));

		if (!(startPiece instanceof Pawn) && !(startPiece instanceof King)) {
			String result = null;
			Collection<Piece> pieces = game.getPieces(startPiece.getColor());
			for (Piece p : pieces) {
				if (p == startPiece || !p.getClass().equals(startPiece.getClass()))
					continue;
				if (p.isValidMove(game, end)) {
					char startPosition = p.getPosition().getColumn() != startPiece.getPosition().getColumn()? 
							startPiece.getPosition().getNotation().charAt(0) : 
							startPiece.getPosition().getNotation().charAt(1);
					String candidate = game.getPiece(end) == null? 
							String.format("%s%s%s", startPiece.getNotation(), startPosition, end) : 
							String.format("%s%sx%s", startPiece.getNotation(), startPosition, end);
					if (result == null)
						result = candidate;
					else
						result = game.getPiece(end) == null? 
								String.format("%s%s%s", startPiece.getNotation(), start, end) : 
								String.format("%s%sx%s", startPiece.getNotation(), start, end);
				}
			}
			if (result != null)
				return result;
		}
		if (game.getPiece(end) == null)
			return String.format("%s%s", startPiece.getNotation(), end);
		return String.format("%sx%s", startPiece instanceof Pawn? start.getNotation().charAt(0) : startPiece.getNotation(), end);
	}

	@Override
	protected void makeMove(Game game, Coordinate start, Coordinate end) {
		Piece p = game.getPiece(start);
		Piece toBeCaptured = game.getPiece(end); 
		if (toBeCaptured != null)
			game.removePiece(toBeCaptured);
		
		p.setPosition(end);
		game.getSquare(start).setPiece(null);
		game.getSquare(end).setPiece(p);
	}
}
